<?php
/**
 * MQTT 消息调试命令行工具
 * 支持测试 Vendor1 和 Vendor2 协议
 *
 * 使用方法:
 * php test_mqtt_cli.php vendor2 "rziot/zftx_w06/861179035726231/result" '{"imei":"861179035726231",...}'
 * php test_mqtt_cli.php vendor1 "tc/device/out/1C3426522542" '{"device_info":{...},...}'
 */

// 定义应用根目录
define('APP_PATH', __DIR__ . '/application/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');

require __DIR__ . '/thinkphp/base.php';

use app\service\MessageParser\MessageParserFactory;
use app\service\MqttMessageHandler;
use think\Log;

// 解析命令行参数
$vendor = $argv[1] ?? 'vendor2';
$topic = $argv[2] ?? 'rziot/zftx_w06/861179035726231/result';
$messageJson = $argv[3] ?? null;

// 默认消息数据
if (!$messageJson) {
    if ($vendor === 'vendor2') {
        $messageJson = '{"c":"zidianmao","imei":"861179035726231","iccid":"89860325247554801710","ssid":"MIFI-8915","password":"1234567890","opname":"46003","dbm":"-86","simSwitch":"2","ip":"192.168.100.1","lac":"30555","version":"JZ12SC_ZIDIANMAO_20251200_V1.0.0","cell_id":"27235605","speed_downlink":0,"speed_uplink":0,"sn":"86117903572623","boot_time":"1236643","count":"8","hidden":"0"}';
    } else {
        echo "请提供消息数据\n";
        exit(1);
    }
}

$messageData = json_decode($messageJson, true);

if (!is_array($messageData)) {
    echo "❌ JSON 解析失败\n";
    exit(1);
}

echo "========== MQTT 消息调试工具 ==========\n";
echo "协议: {$vendor}\n";
echo "主题: {$topic}\n";
echo "消息: " . json_encode($messageData, JSON_UNESCAPED_UNICODE) . "\n\n";

try {
    // 检测协议
    echo "【步骤1】检测协议...\n";
    $parser = MessageParserFactory::detect($topic, $messageData);
    
    if (!$parser) {
        echo "❌ 未检测到合适的解析器\n";
        exit(1);
    }
    
    echo "✅ 检测到: " . get_class($parser) . "\n\n";
    
    // 解析消息
    echo "【步骤2】解析消息...\n";
    $parsedData = $parser->parse($topic, $messageData);
    
    if (!$parsedData) {
        echo "❌ 消息解析失败\n";
        exit(1);
    }
    
    echo "✅ 解析成功\n";
    echo "   关键字段:\n";
    echo "   - IMEI: " . ($parsedData['IMEI'] ?? 'N/A') . "\n";
    echo "   - MAC: " . ($parsedData['mac'] ?? 'N/A') . "\n";
    echo "   - ICCID: " . ($parsedData['iccid'] ?? 'N/A') . "\n";
    echo "   - 信号强度: " . ($parsedData['signal_strength'] ?? 'N/A') . "\n";
    echo "   - dBm: " . ($parsedData['dbm'] ?? 'N/A') . "\n\n";
    
    // 处理消息
    echo "【步骤3】处理消息...\n";
    $handler = new MqttMessageHandler();
    $result = $handler->handle($topic, $messageData);
    
    if (!$result) {
        echo "❌ 消息处理失败\n";
        exit(1);
    }
    
    echo "✅ 消息处理成功\n\n";
    
    // 保存到数据库
    echo "【步骤4】保存到数据库...\n";
    $handler->flush();
    echo "✅ 消息已保存到数据库\n\n";
    
    echo "========== 调试完成 ==========\n";
    
} catch (\Throwable $e) {
    echo "❌ 异常: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
    exit(1);
}

